package xyz.ag.Filiter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class loginFilter
 */
@WebFilter("/loginFilter")
public class loginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public loginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;//转换对象
		HttpServletResponse resp = (HttpServletResponse) response;
		
		String uri = req.getRequestURI();

		if(uri.endsWith(".css")||uri.endsWith(".js")||uri.endsWith(".ttf")//静态资源方形
				|| uri.endsWith(".eot")|| uri.endsWith(".woff")
				|| uri.endsWith(".woff2")|| uri.endsWith(".svg")) {
			chain.doFilter(request, response);
			return;
		}
		
		if(uri.endsWith("/") || uri.endsWith("myindex.jsp")||uri.endsWith("showlist.jsp")) {
			chain.doFilter(request, response);
			return;
		}
		HttpSession session = req.getSession();
		Object user = session.getAttribute("user");//找不到用户就回主页
		if(null==user) {
			resp.sendRedirect("/");
			return;
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
